$(document).ready(function() {
    // 检查登录状态
    const userId = localStorage.getItem('userId');
    const role = localStorage.getItem('role');
    
    if (!userId || role !== '0') {
        window.location.href = '../index.html';
        return;
    }

    // 加载订单列表
    loadOrders();

    // 退出登录
    $('#logout').click(function(e) {
        e.preventDefault();
        localStorage.removeItem('userId');
        localStorage.removeItem('role');
        window.location.href = '../index.html';
    });
});

function loadOrders() {
    const userId = localStorage.getItem('userId');
    
    $.ajax({
        url: `/api/order/list/${userId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const orders = response.data;
                const container = $('#ordersList');
                container.empty();
                
                if (orders.length === 0) {
                    container.html(`
                        <div class="empty-orders">
                            <h3>暂无订单</h3>
                            <p>快去 <a href="index.html">商品列表</a> 挑选喜欢的商品吧！</p>
                        </div>
                    `);
                    return;
                }
                
                orders.forEach(order => {
                    container.append(`
                        <div class="order-card">
                            <div class="order-header">
                                <div class="order-id">订单号: ${order.orderId}</div>
                                <div class="order-status">${getStatusText(order.status)}</div>
                            </div>
                            <div class="order-details" id="details-${order.orderId}">
                                <!-- 订单详情将通过AJAX加载 -->
                            </div>
                            <div class="order-footer">
                                <div class="order-time">下单时间: ${new Date(order.orderTime).toLocaleString()}</div>
                                <div class="order-total">总计: ¥${order.totalMoney.toFixed(2)}</div>
                            </div>
                        </div>
                    `);
                    
                    // 加载订单详情
                    loadOrderDetails(order.orderId);
                });
            } else {
                showMessage(response.message || '加载订单失败', 'error');
            }
        },
        error: function() {
            showMessage('加载订单失败，请重试', 'error');
        }
    });
}

function loadOrderDetails(orderId) {
    $.ajax({
        url: `/api/order/details/${orderId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const details = response.data;
                const container = $(`#details-${orderId}`);
                
                details.forEach(detail => {
                    container.append(`
                        <div class="order-item">
                            <div class="item-name">${detail.commodityName}</div>
                            <div class="item-price">¥${detail.price.toFixed(2)} × ${detail.amount}</div>
                            <div class="item-total">¥${detail.money.toFixed(2)}</div>
                        </div>
                    `);
                });
            }
        }
    });
}

function getStatusText(status) {
    switch(status) {
        case 1: return '<span class="status-pending">待处理</span>';
        case 2: return '<span class="status-accepted">已接受</span>';
        case 3: return '<span class="status-rejected">已拒绝</span>';
        default: return '<span class="status-unknown">未知状态</span>';
    }
}

// 添加消息提示函数
function showMessage(message, type = 'success') {
    const messageDiv = $('<div>')
        .addClass('message')
        .addClass(type)
        .text(message)
        .css({
            'position': 'fixed',
            'top': '20px',
            'left': '50%',
            'transform': 'translateX(-50%)',
            'padding': '10px 20px',
            'border-radius': '4px',
            'background': type === 'success' ? '#4CAF50' : '#f44336',
            'color': 'white',
            'z-index': 1000,
            'opacity': 0
        });

    $('body').append(messageDiv);
    messageDiv.animate({ opacity: 1 }, 300);

    setTimeout(() => {
        messageDiv.animate({ opacity: 0 }, 300, function() {
            $(this).remove();
        });
    }, 2000);
} 